var prefix = jsctx + "/enterpriseMemberApply";
var enterpriseMemberApply = (function () {
    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });

    function reLoad() {
        $('#exampleTable').bootstrapTable('refresh');
        load();
    };

    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        }, 10)
    };
    var h = $(window).height() - 80;

    function load() {
        $('#exampleTable')
            .bootstrapTable({
                method: 'get',
                url: prefix + "/listEnterpriseMemberApply",
                iconSize: 'outline',
                toolbar: '#exampleToolbar',
                striped: false,
                dataType: "json",
                pagination: true,
                singleSelect: false,
                pageList: [10, 20, 30],
                pageSize: 10,
                pageNumber: 1,
                sidePagination: "server",
                cache: false,
                height: h,
                paginationShowPageGo: true,
                rightFixedColumns: true,
                queryParams: function (params) {
                    return {
                        limit: params.limit,
                        offset: (params.offset / params.limit) + 1,
                        enterpriseName: $("#enterpriseName").val(),
                    };
                },
                columns: [
                    {
                        field: 'number',
                        title: '序号',
                        width: '100', align: 'center',
                        formatter: function (value, row, index) {
                            return index + 1;
                        }
                    },
                    {field: 'enterpriseId', title: '企业ID',width: '100', align: 'center'},
                    {field: 'enterpriseName', title: '企业名称',width: '100', align: 'center'},
                    {field: 'enterpriseLevel', title: '企业等级',width: '100', align: 'center'},
                    {field: 'enterpriseCredit', title: '统一社会信用代码',width: '150', align: 'center'},
                    {field: 'taxPayerCode', title: '纳税人识别号',width: '150', align: 'center'},
                    {field: 'enterpriseBank', title: '开户行',width: '100', align: 'center'},
                    {field: 'enterpriseBankAccount', title: '银行账号',width: '100', align: 'center'},
                    {field: 'enterpriseOwner', title: '法人姓名',width: '50', align: 'center'},
                    {field: 'ownerMobile', title: '法人电话',width: '50', align: 'center'},
                    {field: 'contactName', title: '负责人姓名',width: '50', align: 'center'},
                    {field: 'phone', title: '负责人电话',width: '50', align: 'center'},
                    {field: 'address', title: '地址',width: '150', align: 'center'},
                    {field: 'creditAmount',width: '100', title: '授信额度', align: 'center'},
                    {field: 'remainCreditAmount',width: '100', title: '授信额剩余余额', align: 'center'},
                    {field: 'allRechargeEnterpriseAccount', title: '累计充值额',width: '100', align: 'center'},
                    {field: 'enterpriseAccount', title: '账户余额',width: '100', align: 'center'},
                    {
                        field: 'enterpriseStatus', title: '状态', width: '100', align: 'center',
                        formatter: function (value, row, index) {
                            if (row.enterpriseStatus != null) {
                                if (row.enterpriseStatus == '0') {
                                    return  '<input class="tgl tgl-skewed" onclick="enterpriseMemberApply.onSwitchChange(' + row.enterpriseId +',1 )" id="cb'+row.enterpriseId+'" type="checkbox"><label class="tgl-btn" data-tg-off="启动" data-tg-on="禁用" for="cb'+row.enterpriseId+'"></label>'
                                } else {
                                    return '<input class="tgl tgl-skeweds"  onclick="enterpriseMemberApply.onSwitchChange(' + row.enterpriseId +',0 )" id="cb'+row.enterpriseId+'" type="checkbox" value=' + row.enterpriseId +'> <label class="tgl-btn isok" data-tg-off="禁用" data-tg-on="启动" for="cb'+row.enterpriseId+'"></label>'
                                }
                            } else {
                                return null;
                            }

                        }
                    },
                    {field: 'createdTime', title: '创建时间',width: '150', align: 'center'},
                    {
                        field: 'status',
                        title: '审核状态',
                        width: '100', align: 'center',
                        formatter: function (value, row, index) {
                            if (row.status == '0') {
                                return '<span class="label label-success">待审核</span>';
                            } else if (row.status == '1') {
                                return '<span class="label label-info">审核通过</span>';
                            } else if (row.status == '2') {
                                return '<span class="label label-danger">审核未通过</span>';
                            }
                        }
                    },
                    {
                        title: '操作',
                        field: 'orderId',
                        width: '150', align: 'center',
                        class: 'operate-td',
                        formatter: function (value, row, index) {
                            var a = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" mce_href="#" title="编辑" onclick="enterpriseMemberApply.editEnterpriseApply(\''
                                + row.enterpriseApplyId + '\')">编辑</a> ';
                            var aa = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" mce_href="#" title="编辑" onclick="enterpriseMemberApply.editEnterprise(\''
                                + row.enterpriseId + '\')">编辑</a> ';
                            var b = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" mce_href="#" title="详情" onclick="enterpriseMemberApply.detailEnterpriseApply(\''
                                + row.enterpriseApplyId + '\')">详情</a> ';
                            var bb = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" mce_href="#" title="详情" onclick="enterpriseMemberApply.detailEnterprise(\''
                                + row.enterpriseId + '\')">详情</a> ';
                            var c = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" mce_href="#" title="编辑" onclick="enterpriseMemberApply.enterpriseSubmember(\''
                                + row.enterpriseId + '\')">企业成员</a> ';
                            var d = '<a class="btn btn-danger btn-sm ' + has_edit + '" href="#" mce_href="#" title="删除" onclick="enterpriseMemberApply.deleteEnterpriseApply(\''
                                + row.enterpriseApplyId + '\')">删除</a> ';
                            var e = '<a class="btn btn-primary btn-sm' + has_edit + '" href="#" title="审核" onclick="enterpriseMemberApply.showModel(\''
                                + row.enterpriseApplyId + '\')">审核</a> ';
                            var f = '<a class="btn btn-danger btn-sm' + has_edit + '" href="#" title="充值" onclick="enterpriseMemberApply.rechargeAccount(\''
                                + row.enterpriseId + '\')">充值</a> ';
                            var g = '<a class="btn btn-danger btn-sm' + has_edit + '" href="#" title="充值" onclick="enterpriseMemberApply.chanageCredit(\''
                                + row.enterpriseId + '\')">授信额</a> ';

                            var operate = '';

                            if (row.status == '1') {
                                operate = operate + aa + bb + c + f + g;
                            } else {
                                if (row.status == '0') {
                                    operate = operate + e;
                                }
                                operate = operate + a + b + d;
                            }
                            return operate;
                        }
                    }
                ], onLoadSuccess: function () {

                }, onPageChange: function () {

                }
            });
    };
    /**
     * 导出列表
     */
    function exportList() {
        $.fileDownload(prefix + "/export", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                enterpriseName: $("#enterpriseName").val(),
                offset: $('.active .page-link').text(),
                limit: $(".page-size").text()
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    }

        function onSwitchChange (isId, state) {


            $.ajax({
                type: "post",
                dataType: "json",
                async: false,
                url: jsctx + "/enterpriseMember/updateEnterpriseStatus",
                data: {
                    status: state ,
                    id: isId
                },
                success: function (data) {
                    reLoad();
                },
                error: function (xhr, error, exception) {
                }
            });
        }



    function addEnterpriseAppy() {
        location.href = prefix + "/add";
    }

    function editEnterpriseApply(enterpriseApplyId) {
        location.href = prefix + "/applyRecord/" + enterpriseApplyId;
    }

    function detailEnterpriseApply(enterpriseApplyId) {
        location.href = prefix + "/detail/" + enterpriseApplyId;
    }

    function editEnterprise(id) {
        location.href = jsctx + "/enterpriseMember/edit/" + id;
    }

    function detailEnterprise(id) {
        location.href = jsctx + "/enterpriseMember/detail/" + id;
    }

    function enterpriseSubmember(id) {
        location.href = jsctx + "/enterpriseMember/enterpriseSubmember/" + id;
    }

    function deleteEnterpriseApply(id) {
        layer.confirm('确定要删除选中的记录？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                type: "post",
                dataType: "json",
                async: false,
                url: prefix + "/delete/" + id,
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("删除成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    /*  模态框  */
    function showModel(id) {
        $('#exampleModal').modal('show');

        $("#submitButton").unbind("click").bind("click", function () {
            $.ajax({
                url: prefix + "/updateEnterpriseApplyForAudit",
                type: "post",
                data: {
                    "id": id,
                    "status": $("#status").val(),
                    "auditRemark": $("#auditRemark").val()
                },
                dataType: "json",
                success: function (data) {
                    if (data.status == 200) {
                        parent.layer.msg("操作成功");
                        $('#exampleModal').on('hidden.bs.modal', function () {
                            document.getElementById("contentForm").reset();
                        })
                        $('#exampleModal').modal('hide')
                        reLoad();
                    } else {
                        parent.layer.alert(data.message);
                        $('#exampleModal').on('hidden.bs.modal', function () {
                            document.getElementById("contentForm").reset();
                        })
                        $('#exampleModal').modal('hide')
                    }
                }
            })
        })

    }

    function rechargeAccount(id) {
        $('#rechargeModal').modal('show');
        $("#rechargeButton").unbind("click").bind("click", function () {
            $.ajax({
                url: jsctx + "/enterpriseMember/updateEnterpriseForRecharge",
                type: "post",
                data: {
                    "id": id,
                    "money": $("#money").val().trim()
                },
                dataType: "json",
                success: function (data) {
                    if (data.status == 200) {
                        parent.layer.msg("操作成功");
                        $('#rechargeModal').on('hidden.bs.modal', function () {
                            document.getElementById("rechargeForm").reset();
                        })
                        $('#rechargeModal').modal('hide')
                        reLoad();
                    } else {
                        parent.layer.alert(data.message);
                        $('#rechargeModal').on('hidden.bs.modal', function () {
                            document.getElementById("rechargeForm").reset();
                        })
                        $('#rechargeModal').modal('hide')
                    }
                }
            })
        })

    }

    function chanageCredit(id) {
        $('#creditModal').modal('show');
        $("#creditButton").unbind("click").bind("click", function () {
            $.ajax({
                url: jsctx + "/enterpriseMember/updateEnterpriseForCredit",
                type: "post",
                data: {
                    "id": id,
                    "creditAmount": $("#creditAmount").val().trim()
                },
                dataType: "json",
                success: function (data) {
                    if (data.status == 200) {
                        parent.layer.msg("操作成功");
                        $('#creditModal').on('hidden.bs.modal', function () {
                            document.getElementById("creditForm").reset();
                        })
                        $('#creditModal').modal('hide')
                        reLoad();
                    } else {
                        parent.layer.alert(data.message);
                        $('#creditModal').on('hidden.bs.modal', function () {
                            document.getElementById("creditForm").reset();
                        })
                        $('#creditModal').modal('hide')
                    }
                }
            })
        })

    }


    return {
        init: init,
        reLoad: reLoad,
        editEnterpriseApply: editEnterpriseApply,
        editEnterprise: editEnterprise,
        detailEnterpriseApply: detailEnterpriseApply,
        detailEnterprise: detailEnterprise,
        deleteEnterpriseApply: deleteEnterpriseApply,
        addEnterpriseAppy: addEnterpriseAppy,
        showModel: showModel,
        enterpriseSubmember:enterpriseSubmember,
        exportList:exportList,
        onSwitchChange:onSwitchChange,
        rechargeAccount:rechargeAccount,
        chanageCredit:chanageCredit
    };
})();

var editEnterpriseApply = (function () {
    function init() {

        validateRule();
    };

    function save() {
        var formData = new FormData($("#frmEnterpriseApply")[0]);
        $.ajax({
            cache: true,
            type: "POST",
            url: prefix + "/saveApplyRecord",
            data: formData,
            processData: false,
            contentType: false,
            async: false,
            error: function (request) {
                parent.layer.alert("请重新登录");
            },
            success: function (data) {
                if (data.status == 200) {
                    parent.layer.msg("成功");
                    javascript:history.back(-1);
                } else {
                    if (data.status == 600) {
                        javascript:history.back(-1);
                    } else {
                        parent.layer.alert(data.message);
                    }
                }
            }
        });
    };

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frmEnterpriseApply").validate({
            rules: {
                enterpriseName: {
                    required: true,
                    maxlength: 25,
                },
                enterpriseCredit: {
                    required: true,
                    maxlength: 18
                },
                taxPayerCode: {
                    required: true,
                    maxlength: 18
                },
                enterpriseBank: {
                    required: true
                },
                enterpriseBankAccount: {
                    required: true
                },
                enterpriseOwner: {
                    required: true
                },
                ownerMobile: {
                    required: true
                },
                contactName: {
                    required: true
                },
                phone: {
                    required: true
                }
            },
            messages: {
                enterpriseName: {
                    required: icon + "请输入",
                    maxlength: icon + "不能超过25位"
                },
                enterpriseCredit: {
                    required: icon + "请输入",
                    maxlength: icon + "不能超过18位"
                },
                taxPayerCode: {
                    required: icon + "请输入",
                    maxlength: icon + "不能超过18位"
                },
                enterpriseBank: {
                    required: icon + "请输入"
                },
                enterpriseBankAccount: {
                    required: icon + "请输入"
                },
                enterpriseOwner: {
                    required: icon + "请输入"
                },
                ownerMobile: {
                    required: icon + "请输入"
                },
                contactName: {
                    required: icon + "请输入负责人"
                },
                phone: {
                    required: icon + "请输入负责人电话"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    };

    return {
        init: init
    };
})();

var addEnterpriseApply = (function () {
    function init() {

        validateRule();
    };

    function save() {
        var formData = new FormData($("#frm")[0]);
        $.ajax({
            cache: true,
            type: "POST",
            url: prefix + "/addEnterpriseApply",
            data: formData,
            processData: false,
            contentType: false,
            async: false,
            error: function (request) {
                parent.layer.alert("Connection error");
            },
            success: function (data) {
                if (data.status == 200) {
                    parent.layer.msg("操作成功");
                    window.history.back();
                } else {
                    parent.layer.alert(data.message)
                }

            },
        });
    };

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frm").validate({
            rules: {
                enterpriseName: {
                    required: true,
                    maxlength: 25
                },
                enterpriseCredit: {
                    required: true,
                    maxlength: 18
                },
                taxPayerCode: {
                    required: true,
                    maxlength: 18
                },
                enterpriseBank: {
                    required: true
                },
                enterpriseBankAccount: {
                    required: true
                },
                enterpriseOwner: {
                    required: true
                },
                ownerMobile: {
                    required: true
                },
                contactName: {
                    required: true
                },
                phone: {
                    required: true
                }
            },
            messages: {
                enterpriseName: {
                    required: icon + "请输入",
                    maxlength: icon + "不能超过25位"
                },
                enterpriseCredit: {
                    required: icon + "请输入",
                    maxlength: icon + "不能超过18位"
                },
                taxPayerCode: {
                    required: icon + "请输入",
                    maxlength: icon + "不能超过18位"
                },
                enterpriseBank: {
                    required: icon + "请输入"
                },
                enterpriseBankAccount: {
                    required: icon + "请输入"
                },
                enterpriseOwner: {
                    required: icon + "请输入"
                },
                ownerMobile: {
                    required: icon + "请输入"
                },
                contactName: {
                    required: icon + "请输入负责人"
                },
                phone: {
                    required: icon + "请输入负责人电话"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    };
    return {
        init: init
    };


})();
